<?php


namespace App\Modules\Order\Criterias;


use Flower\Core\Repository\Contracts\RepositoryInterface;
use Flower\Core\Repository\Criterias\BaseCriterias;

class getOrderServiceListCriteria extends BaseCriterias
{
    public $params;

    public function __construct($storeId, $serviceId, $startDate, $endDate,$user_id=null,$isProfit=0)
    {
        $this->params = [
            'store_id'   => $storeId,
            'service_id' => $serviceId,
            'start_date' => $startDate,
            'end_date'   => $endDate,
            'user_id'   => $user_id,
            'is_profit' =>$isProfit
        ];
    }


    public function apply($model, RepositoryInterface $repository)
    {
        $storeId = $this->params['store_id'];
        $serviceId = $this->params['service_id'];
        $endDate = $this->params['end_date'];
        $startDate = $this->params['start_date'];
        $user_id = $this->params['user_id'];

        $price = $this->params['is_profit'] ? 'profit': 'real_price';
        return $model->with([
            'order' => function ($j) use ($storeId,$user_id,$price) {
                $j->select(['id', 'barber_id',$price, 'profit','finish_time', 'store_id'])->with([
                    'user' => function ($v) {
                        $v->select(['id', 'nick', 'portrait'])->with('picture:id,image');
                    }
                ])->when($user_id,function ($query) use ($user_id){
                    $query->where('barber_id',$user_id);
                })
                    ->where('store_id', '=', $storeId);
            }
        ])->when($this->params['is_profit'],function ($v){
        	$v->with(['service'=>function($k){
		        $k->select(['id','type'])->with(['category'=>function($query){
			        $query->select(['id','resource'])->with('picture:id,image');
		        }]);
	        }]);
        })
	        ->whereRaw('service_id="' . $serviceId . '" and date(created_at) >= "' . $endDate . '" and date(created_at) <= "' . $startDate . '"')->orderBy('created_at','desc');
    }

}
